//
//  YYImagesController.swift
//  YYProject
//
//  Created by FishWithoutWings on 2018/1/15.
//  Copyright © 2018年 陆文宇. All rights reserved.
//

import UIKit

class YYImagesController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var photos = [Photo]()
    var getFrame: ((Int) -> CGRect)!
    
    var currentIndex: Int {
        set {
            guard newValue >= 0 && newValue < photos.count else {
                return
            }
            
            collectionView.contentOffset = CGPoint(x: (UIScreen.main.bounds.width + 15) * CGFloat(newValue), y: 0)
        }
        
        get {
            let index: Int = Int(collectionView.contentOffset.x / screenWidth)
            return index
        }
    }
    
    let collectionView: UICollectionView = {
        let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 15
        flowLayout.minimumInteritemSpacing = 15
        flowLayout.itemSize = UIScreen.main.bounds.size
        flowLayout.scrollDirection = .horizontal
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 15)
        
        let _collectionView: UICollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width + 15, height: UIScreen.main.bounds.size.height), collectionViewLayout: flowLayout)
        _collectionView.isPagingEnabled = true
        _collectionView.backgroundColor = .clear
        return _collectionView
    }()
    var pageControl: UIPageControl!
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    var backgroundView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.view.backgroundColor = .clear
        
        backgroundView = UIView(frame: CGRect(x: 0, y: -64, width: screenWidth, height: screenHeight))
        backgroundView.backgroundColor = UIColor.black
        self.view.addSubview(backgroundView)
        
        collectionView.register(YYImageCollectionViewCell.self, forCellWithReuseIdentifier: "YYImageCollectionViewCell")
        backgroundView.addSubview(collectionView)
        
        createPageControl()
        
        let backTap = UITapGestureRecognizer(target: self, action: #selector(back))
        view.addGestureRecognizer(backTap)
    }
    
    func show(_ index: Int) {
        YYRouter.currentVC.definesPresentationContext = true
        modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        YYRouter.currentVC.present(self, animated: false) {
            YYRouter.currentVC.navigationController?.isNavigationBarHidden = true
        }
        //        YYRouter.currentVC.yy_present(vc: self)
        
        collectionView.performBatchUpdates({
            self.collectionView.delegate = self
            self.collectionView.dataSource = self
            self.collectionView.reloadData()
            self.currentIndex = index
        }) { (_) in
            let frame = self.getFrame(self.currentIndex)
            let imageView = (self.collectionView.cellForItem(at: IndexPath(item: self.currentIndex, section: 0)) as! YYImageCollectionViewCell).zoomImageView.imageView
            let orinialFrame = imageView.frame
            imageView.frame = frame
            delay(0.01, {
                UIView.animate(withDuration: 0.3, animations: {
                    imageView.frame = orinialFrame
                })
            })
        }
    }
    
    @objc func back() {
        YYRouter.currentVC.navigationController?.isNavigationBarHidden = false
        let frame = getFrame(currentIndex)
        let zoomImageView = (collectionView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as! YYImageCollectionViewCell).zoomImageView
        zoomImageView.scrollView.zoomScale = 1
        zoomImageView.scrollView.contentInset = UIEdgeInsets.zero
        UIView.animate(withDuration: 0.3, animations: {
            self.backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
            zoomImageView.imageView.frame = frame
        }) { (_) in
            self.dismiss(animated: false, completion: nil)
            //            self.yy_dismiss()
        }
    }
    
    func createPageControl() {
        pageControl = UIPageControl(frame: CGRect(x: 0, y: screenHeight - 30, width: screenWidth, height: 30))
        pageControl.numberOfPages = photos.count
        pageControl.currentPage = currentIndex
        pageControl.pageIndicatorTintColor = UIColor.gray
        pageControl.currentPageIndicatorTintColor = UIColor.white
        backgroundView.addSubview(pageControl)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: YYImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "YYImageCollectionViewCell", for: indexPath) as! YYImageCollectionViewCell
        
        cell.zoomImageView.scrollView.zoomScale = 1
        if let placeholder = photos[indexPath.item].placeholder {
            cell.zoomImageView.imageView.kf.setImage(with: URL(string: photos[indexPath.item].url!), placeholder: placeholder)
            let height = screenWidth / placeholder.size.width * placeholder.size.height
            cell.zoomImageView.imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: height)
            if height < screenHeight {
                let maxZoomScale = screenHeight / height
                cell.zoomImageView.scrollView.maximumZoomScale = maxZoomScale > 2 ? maxZoomScale : 2
                cell.zoomImageView.imageView.center = CGPoint(x: screenWidth / 2, y: screenHeight / 2)
            }
        } else {
            cell.zoomImageView.imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenWidth)
            cell.zoomImageView.imageView.center = CGPoint(x: screenWidth / 2, y: screenHeight / 2)
            cell.zoomImageView.imageView.kf.setImage(with: URL(string: photos[indexPath.item].url!), placeholder: #imageLiteral(resourceName: "placeImage1-1")) { (image, error, _, _) in
                if error == nil,
                    let image = image {
                    let height = screenWidth / image.size.width * image.size.height
                    cell.zoomImageView.imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: height)
                    if height < screenHeight {
                        let maxZoomScale = screenHeight / height
                        cell.zoomImageView.scrollView.maximumZoomScale = maxZoomScale > 2 ? maxZoomScale : 2
                        cell.zoomImageView.imageView.center = CGPoint(x: screenWidth / 2, y: screenHeight / 2)
                    }
                }
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        (cell as! YYImageCollectionViewCell).zoomImageView.scrollView.zoomScale = 1
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        pageControl.currentPage = currentIndex
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

